"""
模板管理器
负责加载、管理和应用PPT模板配置。
"""

import os
import json
import logging
from typing import Dict, List, Optional, Any
from datetime import datetime
from pathlib import Path

from ..models.template_config import (
    TemplateConfig, TemplateMetadata, TemplateStyle, 
    ColorScheme, FontConfig, LayoutConfig, LayoutType, FontWeight
)

logger = logging.getLogger(__name__)


class TemplateManager:
    """
    模板管理器类
    
    负责模板的加载、缓存、应用和管理
    """
    
    def __init__(self, templates_dir: str = None):
        """
        初始化模板管理器
        
        Args:
            templates_dir: 模板配置文件目录
        """
        self.templates_dir = templates_dir or os.path.join("backend", "app", "templates")
        self.templates_cache: Dict[str, TemplateConfig] = {}
        self.default_templates: Dict[str, Dict] = {}
        
        # 确保模板目录存在
        Path(self.templates_dir).mkdir(parents=True, exist_ok=True)
        
        # 初始化默认模板
        self._init_default_templates()
        
        # 加载所有模板
        self._load_all_templates()
    
    def _init_default_templates(self):
        """初始化默认模板配置"""
        
        # Professional 模板
        self.default_templates["professional"] = {
            "metadata": {
                "id": "professional",
                "name": "专业风格",
                "category": "商务",
                "tags": ["专业", "商务", "正式"],
                "author": "系统",
                "version": "1.0.0",
                "created_at": datetime.now().isoformat(),
                "updated_at": datetime.now().isoformat(),
                "is_active": True
            },
            "style": {
                "name": "professional",
                "display_name": "专业风格",
                "description": "适合商务演示和正式场合的专业模板",
                "color_scheme": {
                    "primary": "#2E86AB",
                    "secondary": "#A23B72", 
                    "accent": "#F18F01",
                    "background": "#FFFFFF",
                    "text_primary": "#333333",
                    "text_secondary": "#666666",
                    "border": "#E0E0E0"
                },
                "fonts": {
                    "title": {
                        "family": "Microsoft YaHei",
                        "size": 32,
                        "weight": "bold",
                        "color": "#2E86AB"
                    },
                    "heading": {
                        "family": "Microsoft YaHei", 
                        "size": 24,
                        "weight": "bold",
                        "color": "#333333"
                    },
                    "body": {
                        "family": "Microsoft YaHei",
                        "size": 16,
                        "weight": "normal",
                        "color": "#333333"
                    },
                    "caption": {
                        "family": "Microsoft YaHei",
                        "size": 12,
                        "weight": "normal", 
                        "color": "#666666"
                    }
                },
                "layouts": {
                    "title_slide": {
                        "type": "title_slide",
                        "margins": {"top": 80, "bottom": 80, "left": 60, "right": 60},
                        "spacing": {"line": 25, "paragraph": 40},
                        "content_area": {"x": 0.1, "y": 0.2, "width": 0.8, "height": 0.6}
                    },
                    "content_slide": {
                        "type": "content_slide", 
                        "margins": {"top": 60, "bottom": 60, "left": 50, "right": 50},
                        "spacing": {"line": 20, "paragraph": 30},
                        "content_area": {"x": 0.1, "y": 0.15, "width": 0.8, "height": 0.7}
                    },
                    "two_column": {
                        "type": "two_column",
                        "margins": {"top": 60, "bottom": 60, "left": 50, "right": 50},
                        "spacing": {"line": 20, "paragraph": 30},
                        "content_area": {"x": 0.05, "y": 0.15, "width": 0.9, "height": 0.7}
                    }
                },
                "border_radius": 5,
                "shadow_enabled": True,
                "animation_enabled": False
            }
        }
        
        # Creative 模板
        self.default_templates["creative"] = {
            "metadata": {
                "id": "creative",
                "name": "创意风格",
                "category": "创意",
                "tags": ["创意", "活泼", "设计"],
                "author": "系统",
                "version": "1.0.0",
                "created_at": datetime.now().isoformat(),
                "updated_at": datetime.now().isoformat(),
                "is_active": True
            },
            "style": {
                "name": "creative",
                "display_name": "创意风格",
                "description": "适合创意展示和设计类演示的活泼模板",
                "color_scheme": {
                    "primary": "#FF6B6B",
                    "secondary": "#4ECDC4",
                    "accent": "#FFE66D",
                    "background": "#FFFFFF",
                    "text_primary": "#2C3E50",
                    "text_secondary": "#7F8C8D",
                    "border": "#BDC3C7"
                },
                "fonts": {
                    "title": {
                        "family": "Microsoft YaHei",
                        "size": 36,
                        "weight": "bold",
                        "color": "#FF6B6B"
                    },
                    "heading": {
                        "family": "Microsoft YaHei",
                        "size": 26,
                        "weight": "bold",
                        "color": "#2C3E50"
                    },
                    "body": {
                        "family": "Microsoft YaHei",
                        "size": 18,
                        "weight": "normal",
                        "color": "#2C3E50"
                    },
                    "caption": {
                        "family": "Microsoft YaHei",
                        "size": 14,
                        "weight": "normal",
                        "color": "#7F8C8D"
                    }
                },
                "layouts": {
                    "title_slide": {
                        "type": "title_slide",
                        "margins": {"top": 70, "bottom": 70, "left": 50, "right": 50},
                        "spacing": {"line": 30, "paragraph": 45},
                        "content_area": {"x": 0.1, "y": 0.2, "width": 0.8, "height": 0.6}
                    },
                    "content_slide": {
                        "type": "content_slide",
                        "margins": {"top": 50, "bottom": 50, "left": 40, "right": 40},
                        "spacing": {"line": 25, "paragraph": 35},
                        "content_area": {"x": 0.1, "y": 0.15, "width": 0.8, "height": 0.7}
                    }
                },
                "border_radius": 10,
                "shadow_enabled": True,
                "animation_enabled": True
            }
        }
        
        # Minimal 模板
        self.default_templates["minimal"] = {
            "metadata": {
                "id": "minimal",
                "name": "简约风格",
                "category": "简约",
                "tags": ["简约", "清爽", "现代"],
                "author": "系统",
                "version": "1.0.0",
                "created_at": datetime.now().isoformat(),
                "updated_at": datetime.now().isoformat(),
                "is_active": True
            },
            "style": {
                "name": "minimal",
                "display_name": "简约风格",
                "description": "简洁清爽的现代化模板，注重内容本身",
                "color_scheme": {
                    "primary": "#34495E",
                    "secondary": "#95A5A6",
                    "accent": "#3498DB",
                    "background": "#FFFFFF",
                    "text_primary": "#2C3E50",
                    "text_secondary": "#7F8C8D",
                    "border": "#ECF0F1"
                },
                "fonts": {
                    "title": {
                        "family": "Microsoft YaHei",
                        "size": 30,
                        "weight": "light",
                        "color": "#34495E"
                    },
                    "heading": {
                        "family": "Microsoft YaHei",
                        "size": 22,
                        "weight": "normal",
                        "color": "#2C3E50"
                    },
                    "body": {
                        "family": "Microsoft YaHei",
                        "size": 16,
                        "weight": "normal",
                        "color": "#2C3E50"
                    },
                    "caption": {
                        "family": "Microsoft YaHei",
                        "size": 12,
                        "weight": "normal",
                        "color": "#7F8C8D"
                    }
                },
                "layouts": {
                    "title_slide": {
                        "type": "title_slide",
                        "margins": {"top": 100, "bottom": 100, "left": 80, "right": 80},
                        "spacing": {"line": 20, "paragraph": 30},
                        "content_area": {"x": 0.15, "y": 0.25, "width": 0.7, "height": 0.5}
                    },
                    "content_slide": {
                        "type": "content_slide",
                        "margins": {"top": 80, "bottom": 80, "left": 60, "right": 60},
                        "spacing": {"line": 18, "paragraph": 25},
                        "content_area": {"x": 0.12, "y": 0.18, "width": 0.76, "height": 0.64}
                    }
                },
                "border_radius": 0,
                "shadow_enabled": False,
                "animation_enabled": False
            }
        }
        
        # Corporate 模板
        self.default_templates["corporate"] = {
            "metadata": {
                "id": "corporate",
                "name": "企业风格",
                "category": "企业",
                "tags": ["企业", "正式", "权威"],
                "author": "系统",
                "version": "1.0.0",
                "created_at": datetime.now().isoformat(),
                "updated_at": datetime.now().isoformat(),
                "is_active": True
            },
            "style": {
                "name": "corporate",
                "display_name": "企业风格",
                "description": "适合企业汇报和正式会议的权威模板",
                "color_scheme": {
                    "primary": "#1B365D",
                    "secondary": "#2E86AB",
                    "accent": "#F39C12",
                    "background": "#FFFFFF",
                    "text_primary": "#2C3E50",
                    "text_secondary": "#5D6D7E",
                    "border": "#D5DBDB"
                },
                "fonts": {
                    "title": {
                        "family": "Microsoft YaHei",
                        "size": 34,
                        "weight": "bold",
                        "color": "#1B365D"
                    },
                    "heading": {
                        "family": "Microsoft YaHei",
                        "size": 24,
                        "weight": "bold",
                        "color": "#2C3E50"
                    },
                    "body": {
                        "family": "Microsoft YaHei",
                        "size": 16,
                        "weight": "normal",
                        "color": "#2C3E50"
                    },
                    "caption": {
                        "family": "Microsoft YaHei",
                        "size": 12,
                        "weight": "normal",
                        "color": "#5D6D7E"
                    }
                },
                "layouts": {
                    "title_slide": {
                        "type": "title_slide",
                        "margins": {"top": 90, "bottom": 90, "left": 70, "right": 70},
                        "spacing": {"line": 28, "paragraph": 42},
                        "content_area": {"x": 0.1, "y": 0.2, "width": 0.8, "height": 0.6}
                    },
                    "content_slide": {
                        "type": "content_slide",
                        "margins": {"top": 70, "bottom": 70, "left": 60, "right": 60},
                        "spacing": {"line": 22, "paragraph": 32},
                        "content_area": {"x": 0.1, "y": 0.15, "width": 0.8, "height": 0.7}
                    }
                },
                "border_radius": 3,
                "shadow_enabled": True,
                "animation_enabled": False
            }
        }
    
    def _load_all_templates(self):
        """加载所有模板配置"""
        try:
            # 首先加载默认模板
            for template_id, template_data in self.default_templates.items():
                try:
                    template_config = TemplateConfig(**template_data)
                    self.templates_cache[template_id] = template_config
                    logger.info(f"加载默认模板成功: {template_id}")
                except Exception as e:
                    logger.error(f"加载默认模板失败 {template_id}: {e}")
            
            # 然后加载自定义模板文件
            if os.path.exists(self.templates_dir):
                for filename in os.listdir(self.templates_dir):
                    if filename.endswith('.json'):
                        template_path = os.path.join(self.templates_dir, filename)
                        self._load_template_file(template_path)
            
            logger.info(f"模板加载完成，共加载 {len(self.templates_cache)} 个模板")
            
        except Exception as e:
            logger.error(f"加载模板配置失败: {e}")
    
    def _load_template_file(self, file_path: str):
        """加载单个模板配置文件"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                template_data = json.load(f)
            
            template_config = TemplateConfig(**template_data)
            template_id = template_config.metadata.id
            
            self.templates_cache[template_id] = template_config
            logger.info(f"加载模板文件成功: {file_path}")
            
        except Exception as e:
            logger.error(f"加载模板文件失败 {file_path}: {e}")
    
    def get_template(self, template_id: str) -> Optional[TemplateConfig]:
        """
        获取指定模板配置
        
        Args:
            template_id: 模板ID
            
        Returns:
            TemplateConfig: 模板配置对象，如果不存在则返回None
        """
        return self.templates_cache.get(template_id)
    
    def get_all_templates(self) -> Dict[str, TemplateConfig]:
        """
        获取所有模板配置
        
        Returns:
            Dict: 所有模板配置的字典
        """
        return self.templates_cache.copy()
    
    def get_templates_by_category(self, category: str) -> Dict[str, TemplateConfig]:
        """
        根据分类获取模板
        
        Args:
            category: 模板分类
            
        Returns:
            Dict: 指定分类的模板配置字典
        """
        return {
            template_id: template_config
            for template_id, template_config in self.templates_cache.items()
            if template_config.metadata.category == category
        }
    
    def get_active_templates(self) -> Dict[str, TemplateConfig]:
        """
        获取所有激活的模板
        
        Returns:
            Dict: 激活的模板配置字典
        """
        return {
            template_id: template_config
            for template_id, template_config in self.templates_cache.items()
            if template_config.metadata.is_active
        }
    
    def apply_template_to_slide(
        self, 
        template_id: str, 
        slide_type: str, 
        content: Dict[str, Any]
    ) -> Dict[str, Any]:
        """
        将模板应用到幻灯片
        
        Args:
            template_id: 模板ID
            slide_type: 幻灯片类型
            content: 幻灯片内容
            
        Returns:
            Dict: 应用模板后的幻灯片配置
        """
        template = self.get_template(template_id)
        if not template:
            logger.warning(f"模板不存在: {template_id}")
            return content
        
        try:
            # 获取对应的布局配置
            layout_key = slide_type if slide_type in template.style.layouts else "content_slide"
            layout_config = template.style.layouts.get(layout_key)
            
            if not layout_config:
                logger.warning(f"布局配置不存在: {layout_key}")
                return content
            
            # 应用模板样式
            styled_content = {
                **content,
                "template_id": template_id,
                "color_scheme": template.style.color_scheme.dict(),
                "fonts": {k: v.dict() for k, v in template.style.fonts.items()},
                "layout": layout_config.dict(),
                "style_properties": {
                    "border_radius": template.style.border_radius,
                    "shadow_enabled": template.style.shadow_enabled,
                    "animation_enabled": template.style.animation_enabled
                }
            }
            
            return styled_content
            
        except Exception as e:
            logger.error(f"应用模板失败 {template_id}: {e}")
            return content
    
    def save_template(self, template_config: TemplateConfig) -> bool:
        """
        保存模板配置到文件
        
        Args:
            template_config: 模板配置对象
            
        Returns:
            bool: 保存是否成功
        """
        try:
            template_id = template_config.metadata.id
            file_path = os.path.join(self.templates_dir, f"{template_id}.json")
            
            # 更新时间戳
            template_config.metadata.updated_at = datetime.now().isoformat()
            
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(template_config.dict(), f, ensure_ascii=False, indent=2)
            
            # 更新缓存
            self.templates_cache[template_id] = template_config
            
            logger.info(f"模板保存成功: {template_id}")
            return True
            
        except Exception as e:
            logger.error(f"保存模板失败: {e}")
            return False
    
    def delete_template(self, template_id: str) -> bool:
        """
        删除模板
        
        Args:
            template_id: 模板ID
            
        Returns:
            bool: 删除是否成功
        """
        try:
            # 不允许删除默认模板
            if template_id in self.default_templates:
                logger.warning(f"不能删除默认模板: {template_id}")
                return False
            
            # 从缓存中删除
            if template_id in self.templates_cache:
                del self.templates_cache[template_id]
            
            # 删除文件
            file_path = os.path.join(self.templates_dir, f"{template_id}.json")
            if os.path.exists(file_path):
                os.remove(file_path)
            
            logger.info(f"模板删除成功: {template_id}")
            return True
            
        except Exception as e:
            logger.error(f"删除模板失败: {e}")
            return False
    
    def get_template_preview(self, template_id: str) -> Dict[str, Any]:
        """
        获取模板预览信息
        
        Args:
            template_id: 模板ID
            
        Returns:
            Dict: 模板预览信息
        """
        template = self.get_template(template_id)
        if not template:
            return {}
        
        return {
            "id": template.metadata.id,
            "name": template.metadata.name,
            "display_name": template.style.display_name,
            "description": template.style.description,
            "category": template.metadata.category,
            "tags": template.metadata.tags,
            "color_scheme": template.style.color_scheme.dict(),
            "preview_image": template.metadata.preview_image
        }
    
    def reload_templates(self):
        """重新加载所有模板"""
        self.templates_cache.clear()
        self._load_all_templates()
        logger.info("模板重新加载完成")


# 全局模板管理器实例
template_manager = TemplateManager()